package com.wisdytech.linkdcs.tool.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.constants.DictKeyConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.dao.ToolMaintainDetailDao;
import com.wisdytech.linkdcs.tool.dao.ToolMaintainItemDao;
import com.wisdytech.linkdcs.tool.dao.ToolMaintainRecordDao;
import com.wisdytech.linkdcs.tool.dao.TtEqToolDao;
import com.wisdytech.linkdcs.tool.model.ToolMaintainDetail;
import com.wisdytech.linkdcs.tool.model.ToolMaintainItem;
import com.wisdytech.linkdcs.tool.model.ToolMaintainRecord;
import com.wisdytech.linkdcs.tool.model.TtEqTool;
import com.wisdytech.linkdcs.tool.service.IToolMaintainRecordService;
import com.wisdytech.linkdcs.tool.vo.ToolMaintainItemVO;
import com.wisdytech.linkdcs.tool.vo.ToolMaintainVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-12
 */
@Service
@Transactional
public class ToolMaintainRecordServiceImpl extends BaseService<ToolMaintainRecordDao, ToolMaintainRecord> implements IToolMaintainRecordService {

    @Resource
    private ToolMaintainRecordDao toolMaintainRecordDao;

    @Resource
    private ToolMaintainDetailDao toolMaintainDetailDao;
	@Resource
    private ToolMaintainItemDao toolMaintainItemDao;

    @Resource
    private TtEqToolDao ttEqToolDao;

    @Override
    public Boolean toolMaintain(ToolMaintainVO vo, SysUser operator) {
        Integer operatorCount = 0;
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        if (vo == null || StringUtils.isBlank(vo.getToolCode()))
            throw new ServiceException("参数错误");
        //保存保养记录
        ToolMaintainRecord record = new ToolMaintainRecord();
        record.setToolCode(vo.getToolCode());
        String pkId = BaseUtil.getUUID();
        record.setPkId(pkId);
        record.setDelFlag(CommonConstants.DEL_FLAG);
        record.setCreateDate(new Date());
        record.setCreateUser(operator.getUsername());
        record.setMaintainUser(vo.getMaintainUser());
        record.setMaintainDate(vo.getMaintainDate());
        record.setConfirmUser(vo.getConfirmUser());
        record.setConfirmDate(vo.getConfirmDate());
        record.setRemark(vo.getRemark());
        operatorCount = toolMaintainRecordDao.insert(record);

        //保存保养项明细
        List<ToolMaintainItemVO> list = vo.getMaintainItemList();
        for (ToolMaintainItemVO itemVO : list) {
            ToolMaintainDetail detail = new ToolMaintainDetail();
            detail.setPkId(BaseUtil.getUUID());
            detail.setCreateUser(operator.getUsername());
            detail.setCreateDate(new Date());
            detail.setDelFlag(CommonConstants.DEL_FLAG);
            detail.setRecordId(pkId);
			// 查询当前该保养项的快照版本
            ToolMaintainItem item = toolMaintainItemDao.selectById(itemVO.getMaintainItemId());
            // 关联id改为version，即当前版本快照的id
            detail.setItemId(item.getVersion());

            detail.setMaintainResult(itemVO.getMaintainResult());
            detail.setRemark(itemVO.getRemark());
            //TODO 循环操作数据库 应该改成 一次批量插入 但是mysql和oracle批量插入数据的语法不同，为兼容暂且如果
            toolMaintainDetailDao.insert(detail);
        }
        //更新下次保养日期和上次保养日期
        TtEqTool tool = new TtEqTool();
        TtEqTool params = new TtEqTool();
        params.setToolCode(vo.getToolCode());
        params.setDelFlag(CommonConstants.DEL_FLAG);
        //查询该工装保养周期
        TtEqTool t = ttEqToolDao.selectOne(params);
        //上次保养日期为这次保养日期
        tool.setLastMaintainDate(vo.getMaintainDate());
        //下次保养日期为这次保养日期加保养周期
        tool.setNextMaintainDate(getAfterDate(t.getMaintainCycle().intValue(),vo.getMaintainDate()));

        //hack 方法 因为在TtEqTool中设置了mp的FieldStrategy 为ignore用来更新空值，所以此处如果不加的话，值会被更新掉
        tool.setMaintainCycle(t.getMaintainCycle());
        tool.setCheckoutCycle(t.getCheckoutCycle());

        EntityWrapper<TtEqTool> ew = new EntityWrapper<>();
        ew.eq("tool_code",vo.getToolCode())
                .eq("del_flag",CommonConstants.DEL_FLAG);
        ttEqToolDao.update(tool,ew);
        return operatorCount > 0;
    }

    @Override
    public PageInfo<TtEqTool> getToolMaintainRecordByFilter(String toolCode, String toolName, String toolModel, String toolType, String opCode, String maintainDateStart, String maintainDateEnd, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        params.put("toolTypeParentKey", DictKeyConstants.TOOL_TYPE_PARENT_KEY);
        if (StringUtils.isNotBlank(toolCode)) {
            params.put("toolCode", toolCode);
        }
        if (StringUtils.isNotBlank(toolName)) {
            params.put("toolName", toolName);
        }
        if (StringUtils.isNotBlank(toolModel)) {
            params.put("toolModel", toolModel);
        }
        if (StringUtils.isNotBlank(toolType)) {
            params.put("toolType", toolType);
        }
        if (StringUtils.isNotBlank(opCode)) {
            params.put("opCode", opCode);
        }
        if (StringUtils.isNotBlank(maintainDateStart)) {
            params.put("maintainDateStart", maintainDateStart);
        }
        if (StringUtils.isNotBlank(maintainDateEnd)) {
            params.put("maintainDateEnd", maintainDateEnd);
        }
        List<TtEqTool> list = this.beforeList(TtEqToolDao.class, filter).getToolMaintainedList(params);
        return new PageInfo<>(list);
    }

    @Override
    public ToolMaintainVO getToolMaintainResult(String pkId) {
        if (StringUtils.isBlank(pkId)) {
            return null;
        }
        //查询工装保养信息
        ToolMaintainRecord record = toolMaintainRecordDao.getToolMaintainRecord(pkId);
        Optional.ofNullable(record)
                .filter(x->StringUtils.isNotBlank(x.getToolCode()))
                .filter(x->StringUtils.isNotBlank(x.getPkId()))
                .orElseThrow(()->new ServiceException("校验记录无效"));
        ToolMaintainVO vo = new ToolMaintainVO();
        vo.setToolCode(record.getToolCode());
        vo.setToolName(record.getToolName());
        vo.setMaintainUserWorkNo(record.getMaintainUserWorkNo());
        vo.setMaintainUser(record.getMaintainUser());
        vo.setMaintainDate(record.getMaintainDate());
        vo.setConfirmDate(record.getConfirmDate());
        vo.setConfirmUser(record.getConfirmUser());
        vo.setRemark(record.getRemark());

        //查询检验项明细
        Map<String, Object> params = new HashMap<>();
        params.put("toolCode",record.getToolCode());
        params.put("recordId",record.getPkId());
        List<ToolMaintainItemVO> list = this.toolMaintainDetailDao.getMaintainResultDetail(params);
        vo.setMaintainItemList(list);
        return vo;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past 天数
     * @return Date
     */
    private Date getAfterDate(int past, Date date) {
        Calendar calendar = Calendar.getInstance();
        if(date!=null) calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        return calendar.getTime();
    }
}
